<template>
	<view class="search-container">
		<!-- 搜索框 -->
		<view class="search-header">
			<view class="search-box">
				<input type="text" v-model="searchKeyword" placeholder="请输入搜索关键词" @confirm="handleSearch"
					confirm-type="search" class="search-input" />
				<text class="clear-icon" v-if="searchKeyword" @tap="clearSearch">×</text>
			</view>
			<text class="cancel-btn" @tap="goBack">取消</text>
		</view>

		<!-- 排序选项 -->
		<view class="sort-options" v-if="searchResults.length > 0">
			<picker :range="sortOptions" range-key="label" @change="onSortChange" :value="sortIndex">
				<view class="picker-box">
					<text>{{ sortOptions[sortIndex].label }}</text>
					<text class="sort-icon">▼</text>
				</view>
			</picker>
		</view>

		<!-- 搜索历史 -->
		<view class="search-history" v-if="!searchKeyword && searchHistory.length > 0">
			<view class="history-header">
				<text class="title">搜索历史</text>
				<text class="clear-history" @tap="clearHistory">清空历史</text>
			</view>
			<view class="history-list">
				<text v-for="(item, index) in searchHistory" :key="index" class="history-item"
					@tap="searchWithHistory(item)">{{ item }}</text>
			</view>
		</view>

		<!-- 搜索结果 -->
		<view class="goods-list" v-if="searchResults.length > 0">

			<view class="goods-item" v-for="item in searchResults" :key="item.goods_id"
				@click="goToDetail(item.goods_id)">
				<image class="goods-image" mode="aspectFill" :src="item.img_url"></image>
				<view class="goods-info">
					<view class="goods-title">{{ item.title }}</view>
					<view class="goods-price">
						<text class="price-symbol">¥</text>
						<text class="price">{{ item.sell_price }}</text>
						<text class="sales">已售 {{ item.sales_count }}</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 无搜索结果 -->
		<view class="no-result" v-if="hasSearched && searchResults.length === 0">
			<text>暂无相关商品</text>
		</view>
	</view>
</template>

<script setup>
import { ref } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app';
import { reqSearchGoods } from '@/api/index';

// 响应式状态
const searchKeyword = ref('')
const searchHistory = ref([])
const searchResults = ref([])
const hasSearched = ref(false)
const sortIndex = ref(0)

// 排序选项
const sortOptions = [
	{ label: '销量', value: 'buy' },
	{ label: '好评', value: 'likes' },
	{ label: '价格', value: 'sell_price' }
]

// 排序相关状态
const currentSort = ref('buy') // 默认按销量排序

// 生命周期钩子
onLoad(() => {
	// 从本地存储获取搜索历史
	try {
		const history = uni.getStorageSync('searchHistory')
		if (history) {
			searchHistory.value = JSON.parse(history)
		}
	} catch (e) {
		console.error('获取搜索历史失败', e)
	}
})

// 处理搜索
const handleSearch = async () => {
	if (!searchKeyword.value.trim()) {
		searchResults.value = []
		hasSearched.value = false
		return
	}

	hasSearched.value = true
	// 保存搜索历史
	saveSearchHistory(searchKeyword.value)

	try {
		const response = await reqSearchGoods({
			value: searchKeyword.value,
			sort: currentSort.value,
			page: 1,
			pagesize: 10
		})
		console.log('搜索返回的完整数据：', response)

		// 检查返回的数据结构
		if (response && Array.isArray(response)) {
			searchResults.value = response.map(item => {
				console.log('商品数据：', item)
				return {
					...item,
					goods_id: item.id || item.goods_id // 确保goods_id存在
				}
			})
		} else {
			searchResults.value = []
			throw new Error('返回数据格式错误')
		}

		if (searchResults.value.length === 0) {
			uni.showToast({
				title: '暂无搜索结果',
				icon: 'none'
			})
		}
	} catch (error) {
		console.error('搜索失败', error)
		uni.showToast({
			title: '搜索失败，请重试',
			icon: 'none'
		})
		searchResults.value = []
	}
}

// 修改onShow钩子
onShow(() => {
	if (searchKeyword.value.trim()) {
		handleSearch()
	}
})

// 保存搜索历史
const saveSearchHistory = (keyword) => {
	const index = searchHistory.value.indexOf(keyword)
	if (index > -1) {
		searchHistory.value.splice(index, 1)
	}
	searchHistory.value.unshift(keyword)
	// 限制历史记录最多10条
	if (searchHistory.value.length > 10) {
		searchHistory.value.pop()
	}
	// 保存到本地存储
	uni.setStorageSync('searchHistory', JSON.stringify(searchHistory.value))
}

// 使用历史记录搜索
const searchWithHistory = (keyword) => {
	searchKeyword.value = keyword
	handleSearch()
}

// 清空搜索框
const clearSearch = () => {
	searchKeyword.value = ''
	searchResults.value = []
	hasSearched.value = false
}

// 清空历史记录
const clearHistory = () => {
	uni.showModal({
		title: '提示',
		content: '确定要清空搜索历史吗？',
		success: (res) => {
			if (res.confirm) {
				searchHistory.value = []
				uni.removeStorageSync('searchHistory')
			}
		}
	})
}

const goBack = () => {
	uni.navigateBack()
}
// 跳转到详情页
const goToDetail = (id) => {
	console.log('id', id)
	if (!id) {
		uni.showToast({
			title: '商品ID不存在',
			icon: 'none'
		})
		return
	}

	uni.navigateTo({
		url: `/pages/goods_package/goodsdetail/goodsdetail?id=${id}`,
		fail: (err) => {
			console.error('跳转失败', err)
			uni.showToast({
				title: '跳转失败，请重试',
				icon: 'none'
			})
		}
	})
}

// 处理排序变化
const onSortChange = (e) => {
	sortIndex.value = e.detail.value
	currentSort.value = sortOptions[sortIndex.value].value
	handleSearch() // 重新搜索以应用新的排序
}
</script>

<style lang="scss" scoped>
.search-container {
	padding: 20rpx;
	background-color: #f6f6f6;
	min-height: 100vh;
}

.search-header {
	display: flex;
	align-items: center;
	padding: 20rpx 0;

	.search-box {
		flex: 1;
		position: relative;
		margin-right: 20rpx;

		.search-input {
			background-color: #fff;
			height: 72rpx;
			border-radius: 36rpx;
			padding: 0 60rpx 0 30rpx;
			font-size: 28rpx;
		}

		.clear-icon {
			position: absolute;
			right: 20rpx;
			top: 50%;
			transform: translateY(-50%);
			font-size: 40rpx;
			color: #999;
			padding: 10rpx;
		}
	}

	.cancel-btn {
		font-size: 28rpx;
		color: #333;
	}
}

.sort-options {
	margin: 20rpx 0;
	background-color: #fff;
	border-radius: 8rpx;
	padding: 0 20rpx;

	.picker-box {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 80rpx;
		font-size: 28rpx;
		color: #333;

		.sort-icon {
			font-size: 24rpx;
			color: #999;
			margin-left: 10rpx;
		}
	}
}

.search-history {
	background-color: #fff;
	border-radius: 12rpx;
	padding: 20rpx;
	margin-top: 20rpx;

	.history-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;

		.title {
			font-size: 28rpx;
			color: #333;
			font-weight: bold;
		}

		.clear-history {
			font-size: 24rpx;
			color: #999;
		}
	}

	.history-list {
		display: flex;
		flex-wrap: wrap;

		.history-item {
			background-color: #f5f5f5;
			padding: 10rpx 20rpx;
			border-radius: 30rpx;
			font-size: 24rpx;
			color: #666;
			margin: 10rpx 20rpx 10rpx 0;
		}
	}
}

// 商品列表样式
.goods-list {
	margin-top: 20rpx;
	display: flex;
	flex-wrap: wrap;
	justify-content: space-between;

	.goods-item {
		width: 345rpx;
		background-color: #fff;
		margin-bottom: 20rpx;
		border-radius: 12rpx;
		overflow: hidden;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);

		.goods-image {
			width: 100%;
			height: 345rpx;
			display: block;
		}

		.goods-info {
			padding: 16rpx;

			.goods-title {
				font-size: 28rpx;
				color: #333;
				line-height: 1.4;
				height: 80rpx;
				overflow: hidden;
				text-overflow: ellipsis;
				display: -webkit-box;
				-webkit-line-clamp: 2;
				-webkit-box-orient: vertical;
			}

			.goods-price {
				margin-top: 16rpx;
				display: flex;
				align-items: baseline;

				.price-symbol {
					font-size: 24rpx;
					color: #ff4444;
				}

				.price {
					font-size: 32rpx;
					color: #ff4444;
					font-weight: bold;
					margin-right: 16rpx;
				}

				.sales {
					font-size: 24rpx;
					color: #999;
				}
			}
		}
	}
}

.no-result {
	text-align: center;
	padding: 100rpx 0;
	color: #999;
	font-size: 28rpx;
}
</style>
